/*
    The MIT License

    Copyright (c) 2010 IFMO/GameDev Studio

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*/

#include "ui.h"

using namespace rapidxml;


/*-----------------------------------------------------------------------------
	Font class declaration :
-----------------------------------------------------------------------------*/

class EUIFont : public IUIFont {
	public:
							EUIFont				( const EString path );
							~EUIFont			( void );
		virtual void		DrawString			( float x, float y, EString text, const EColor &color );
		virtual float		StringLength		( EString text );
		virtual float		GetLineHeight		( void ) const		{ return line_height; }
		virtual float		GetCharWidth		( char ch ) const	{ return char_info[ch].xadvance; }

	public:
		EString	path;
				
	protected:
		struct fontCharInfo_s {
				float	xadvance;
				ETexCoord	uv0;
				ETexCoord	uv1;
				EVector		offset;
				EVector		glyph_size;
			};
			
		EString			font_face;
		EString			font_image;
		float			line_height;
		float			baseline;
		float			scale_w, scale_h;
		fontCharInfo_s	char_info[256];
		signed char		kernings[256][256]; // [first][second]
		
		std::vector<uint16_t>	char_width;
	};


/*-----------------------------------------------------------------------------
	Font class implementation :
-----------------------------------------------------------------------------*/

IPxUIFont EUserInterface::CreateFont( const EString font )
{
	for (uint i=0; i<fonts.size(); i++) {
		if ( fonts[i].as<EUIFont>()->path == font ) {
			return fonts[i];
		}
	}
	
	IPxUIFont	new_font = new EUIFont( font );
	fonts.push_back( new_font );
	
	return new_font;
}


//
//	EFont::EFont
//
EUIFont::EUIFont( const EString path )
{
	this->path	=	path;

	LOGF(va("Loading font : %s", path.CStr()));
	
	//
	//	Initial values :
	//
	memset(kernings, 0, sizeof(kernings));
	memset(char_info, 0, sizeof(char_info));
	line_height	=	8;
	baseline	=	0;
	scale_h		=	1;
	scale_w		=	1;
	font_face	=	"";
	font_image	=	"*white";			// simple white texture
	
	//
	//	Read font description XML-file :
	//
	try {


		IHrFile	file	=	FileSystem()->openFile( path.CStr(), FS_OPEN_READ );
		IPxBlob blob	=	file->stringBlob();
		file = NULL;

		//	parse XML :
		xml_document<>	xdoc;
		xdoc.parse<0>((char*)blob->GetBufferPointer());
		
		xml_node<> *xfont		=	xdoc.first_node("font");
		
		if (!xfont) {
			RUNTIME_ERROR("<font> not found");
		}

		xml_node<> *xinfo		=	xfont->first_node("info");
		xml_node<> *xcommon		=	xfont->first_node("common");
		xml_node<> *xpages		=	xfont->first_node("pages");
		xml_node<> *xchars		=	xfont->first_node("chars");
		xml_node<> *xkernings	=	xfont->first_node("kernings");
		
		if (xinfo) {
			font_face	=	xml_get_attr<char>(xinfo, "face", "");
		}
		
		if (xcommon) {
			line_height =	atof(xml_get_attr(xcommon,	"lineHeight",	"8"));
			baseline	=	atof(xml_get_attr(xcommon,  "base",			"0"));
			scale_w		=	atof(xml_get_attr(xcommon,  "scaleW",		"1"));
			scale_h		=	atof(xml_get_attr(xcommon,  "scaleH",		"1"));
		}
	
		if (xpages) {
			xml_node<> *xpage	=	xpages->first_node();
			font_image = va("%s", xml_get_attr(xpage, "file", "*white"));
		}
		
		if (xchars) {
			xml_node<> *xchar = NULL;
			
			for (xchar = xchars->first_node("char"); xchar; xchar = xchar->next_sibling("char")) 
			{
				uint id = 0;
				float x = 0, y = 0, xoffset = 0, yoffset = 0, xadvance = 0, width=0, height = 0;
				id			=	atoi(xml_get_attr(xchar, "id",		 "0"));
				x			=	atof(xml_get_attr(xchar, "x",		 "0")); 
				y			=	atof(xml_get_attr(xchar, "y",		 "0"));
				xoffset		=	atof(xml_get_attr(xchar, "xoffset",	 "0"));
				yoffset		=	atof(xml_get_attr(xchar, "yoffset",  "0")); 
				width		=	atof(xml_get_attr(xchar, "width",	 "0"));
				height		=	atof(xml_get_attr(xchar, "height",	 "0"));
				xadvance	=	atof(xml_get_attr(xchar, "xadvance", "0"));	 
				
				id &= 0xFF;
				char_info[id].offset.x	= xoffset;
				char_info[id].offset.y	= yoffset;
				char_info[id].xadvance	= xadvance;
				char_info[id].uv0.x = (x) / scale_w;
				char_info[id].uv0.y = (y) / scale_h;
				char_info[id].uv1.x = (x + width) / scale_w;
				char_info[id].uv1.y = (y + height) / scale_h;
				char_info[id].glyph_size.x = width;
				char_info[id].glyph_size.y = height;
			}
		}
		
		if (xkernings) {
			xml_node<> *xkrn = NULL;

			for (xkrn = xkernings->first_node("kerning"); xkrn; xkrn = xkrn->next_sibling("kerning")) 
			{
				uint first = 0;
				uint second = 0;
				int amount = 0;
				
				first	= atoi(xml_get_attr(xkrn, "first",  "0"));
				second	= atoi(xml_get_attr(xkrn, "second", "0"));
				amount	= atoi(xml_get_attr(xkrn, "amount", "0"));
				
				first  &= 0xFF;
				second &= 0xFF;
				
				kernings[first][second] = amount;
			}
		}
	
	
	} catch ( exception &e )	
	{
		LOG_WARNING("%s", e.what());
		return;
	}
	

	//
	//	modify 'font_image' :
	//	
	uint n1		= path.RFind('\\');
	uint n2		= path.RFind('/');
	uint NPOS	= EString::NPOS;
	uint n		= NPOS;
	
	if (n1==NPOS && n2==NPOS) { n = NPOS; }
	if (n1!=NPOS && n2==NPOS) { n = n1; }
	if (n1==NPOS && n2!=NPOS) { n = n2; }
	if (n1!=NPOS && n2!=NPOS) { n = n	= max(n1,n2); }
	
	if (n!=EString::NPOS) {
		EString	dir	=	path.Substr(0, n);
		font_image	=	dir + EString("/") + font_image;
	}
	
}


//
//	EUIFont::~EUIFont
//
EUIFont::~EUIFont( void )
{

}


//
//	EUIFont::DrawString
//
void EUIFont::DrawString( float x, float y, EString text, const EColor &color )
{
	uint len = text.Length();
	std::vector<EUIQuad> quads;
	quads.reserve(len);
	
	EPoint cursor(x, y - line_height);
	
	for (uint i=0; i<len; i++) 
	{
		EUIQuad q;

		uchar ch   = text[i];
		uchar next = text[i+1];

		q.p0	=	cursor + char_info[ch].offset;
		q.p1	=	q.p0   + char_info[ch].glyph_size;
		q.uv0	=	char_info[ch].uv0;
		q.uv1	=	char_info[ch].uv1;
		q.color	=	color;
		
		cursor.x += char_info[ch].xadvance;
		
		cursor.x += (float)kernings[ch][next];
		
		quads.push_back(q);
	}
	
	if (!quads.empty()) {
		rs()->GetUIScene()->RenderQuads( quads.size(), &quads[0], font_image );
	}
}


//
//	EUIFont::StringLength
//
float EUIFont::StringLength( EString text )
{
	float length = 0;
	uint len = text.Length();

	for (uint i=0; i<len; i++) 
	{
		uchar ch   = text[i];
		uchar next = text[i+1];

		length += char_info[ch].xadvance;
		length += kernings[ch][next];
	}
	
	return length;
}








